<input type="hidden" id="controlador" value="MaeSorteo" />
<input type="hidden" id="drawValue" value="0" />
<div>
    <form id="formGenerateTickets" action="../controlador/GestionBoleta.php" method="post">
        <input type="hidden" value="generateTicket" name="operation" />
        <fieldset>
            <legend>Agregar Boleta</legend>
            <table>
                <tr>
                    <td>Sorteo</td>
                    <td>
                        <select id="sorteo" name="codSorteo" required>
                            <script type="text/javascript">
                                cargarOpcionesSelectDesdeControlador($("#sorteo"), "MaeSorteo", "selectAllHTMLSelectFormat");
                            </script>
                        </select>
                    </td>
                    <td style="text-align: left;"><label for="client">Cliente: </label></td>
                    <td>
                        <input type="text" id="client" required />
                        <input type="hidden" id="idClient" name="idClient" value="" />
                    </td>
                    <td>
                        <a id="lnk_agregar" href="#">Agregar cliente</a>
                    </td>
                </tr>
                <tr>
                    <td>Empresa</td>
                    <td>Numero de factura</td>
                    <td>Valor de la compra</td>
                    <td>
                        <a href="#" id="addBill">+ Agregar factura</a> 
                    </td>
                    <td></td>
                </tr>
                <tr id="billInfo">
                    <td>
                        <select id="empresa" name="empresa[]" required>
                            <script type="text/javascript">
                                cargarOpcionesSelectDesdeControlador($("#empresa"), "MaeEmpresa", "selectAllHTMLSelectFormat");
                            </script>
                        </select>                    
                    </td>
                    <td>
                        <input type="text" name="numFactura[]" placeholder="Numero de factura" class="numberBill" required />
                    </td>
                    <td colspan="2">
                        <input type="number" name="valFactura[]" placeholder="Valor de la factura" class="valueBill" required />
                    </td>     
                    <td></td>
                </tr>

                <tr id="bottonGenerateTicket">
                    <td colspan="5">
                        <input type="submit" value="Generar Bono" id="generateTicket" /> 
                    </td>
                </tr>
            </table>            
            <div style="float: left;">
                <p>Valor del sorteo: <span id="spanDrawValue">$0</span></p>
                <p>Total acumulado en compras: <b><span id="total">$0</span></b></p>
                <p>Acumulado anterior: <span id="accumulated">$0</span></p>
                <p>Numero de boletas: <span id="numberTickets">0</span></p>
            </div>
        </fieldset>
    </form>    
</div>

<div id="divInsert" class="popout" title="Nuevo Cliente">
    <form id="formTwo">
        <input type="hidden" name="OPERACION" value="insert"/>
        <table>
            <tr>
                <td>Cod. Cliente</td>
                <td><input type="text" id="codMaeCliente" name="codMaeCliente" /></td>
            </tr>
            <tr>
                <td>Cod. Barrio</td>
                <td>
                    <select id="codMaeBarrio" name="codMaeBarrio">
                        <script type="text/javascript">
                            cargarOpcionesSelectDesdeControlador($("#codMaeBarrio"), "MaeBarrio", "selectAllHTMLSelectFormat");
                        </script>
                    </select>
                </td>
            </tr>
            <tr>
                <td>Nombre Cliente</td>
                <td><input type="text" id="nombreMaeCliente" name="nombreMaeCliente" /></td>
            </tr>                
            <tr>
                <td>Telefono</td>
                <td><input type="text" id="telefono" name="telefono" /></td>
            </tr>                
            <tr>
                <td>Direccion</td>
                <td><input type="text" id="direccion" name="direccion" /></td>
            </tr>                
            <tr>
                <td>EMail</td>
                <td><input type="text" id="eMail" name="eMail" /></td>
            </tr>                
            <tr>
                <td>Activo</td>
                <td><input type="checkbox" id='activo' name='activo' checked="checked"/> </td>
            </tr>  
            <tr>
                <td>                    
                    <input type="submit" value="Guardar" id="createUser" />
                </td>
                <td>
                    <input type="button" value="Cancelar" class="cancelar" />
                </td>
            </tr>
        </table>
    </form>
</div>

<script type="text/javascript">
    $(function() {
        $(".ui-button").hide();

        // ocultando el loader
        $("#loadingGif").remove();
        $(document).ajaxStart(function() {
            $("#contenidoHTML").css({
                "opacity": "1",
                "z-index": "1"
            });
            $("#main").css({
                "opacity": "1",
                "z-index": "1"
            });
        });

        $(document).ajaxStop(function() {
            $("#contenidoHTML").css({"opacity": "1"});
            $("#main").css({"opacity": "1"});
        });

        $("#client").autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: "../controlador/GestionBoleta.php",
                    dataType: "json",
                    data: {
                        operation: "checkClient",
                        nameOrId: request.term
                    },
                    success: function(data) {
                        if (data.hasOwnProperty("ERROR")) {
                            response();
                            showPopupBoxMessage(item.ERROR);
                        } else {
                            response($.map(data.users, function(item) {
                                return {
                                    label: item.cc + " - " + item.name,
                                    value: item.id
                                };
                            }));
                        }
                    },
                    error: function(jqXHR, textStatus, thrownError) {
                        response();
                        alert("Error conecting to database...");
                    }
                });
            },
            minLength: 2,
            select: function(event, ui) {
                $("#idClient").val(ui.item.value);
                $("#client").val(ui.item.label);

                $.ajax({
                    url: "../controlador/GestionBoleta.php",
                    dataType: "json",
                    data: {
                        operation: "GetAccumulated",
                        idCliente: ui.item.value
                    },
                    success: function(data) {
                        if (data !== null && data.hasOwnProperty("ERROR")) {
                            response();
                            showPopupBoxMessage(item.ERROR);
                        }
                        else if (data !== null) {
                            $("#accumulated").text("$" + data);
                        }
                        else {
                            $("#accumulated").text("$0");
                        }
                    }
                });

                return false;
            }
        });

        $("#lnk_agregar").click(function(event) {
            event.preventDefault();
            $("#divInsert").dialog("open");
        });

        $(".cancelar").click(function() {
            $("#divInsert").dialog("close");
        });

        // create new user 
        $("#createUser").click(function() {

            $.ajax({
                type: "POST",
                url: "../controlador/MaeCliente.php",
                dataType: "json",
                data: $("#formTwo").serialize() + "&controlador=MaeCliente",
                success: function(item) {
                    if (item.hasOwnProperty("ERROR")) {
                        showPopupBoxMessage(item.ERROR);
                        return false;
                    }
                    else {
                        $("#idClient").val(item.id);
                        $("#client").val($("#codMaeCliente").val() + " - " + $("#nombreMaeCliente").val());

                        $("#codMaeCliente").val("");
                        $("#codMaeBarrio").val($("#codMaeBarrio option:first").val());
                        $("#nombreMaeCliente").val("");
                        $("#telefono").val("");
                        $("#direccion").val("");
                        $("#eMail").val("");

                        $("#divInsert").dialog("close");
                    }
                },
                error: function(request, status, error) {
                    alert(error);
                }
            });
            return false;
        });

        var calculateFields = function() {

            var total = 0;
            $(".valueBill").each(function() {
                var value = parseInt($(this).val());
                if (isNaN(value)) {
                    value = 0;
                }
                total += value;
            });

            $("#total").text("$" + total);

            var spanDrawValueArray = $("#spanDrawValue").text().split("$");
            var totalArray = $("#total").text().split("$");
            var accumulatedArray = $("#accumulated").text().split("$");

            var total = parseInt(totalArray[1]) + parseInt(accumulatedArray[1]);
            var spanDrawValue = parseInt(spanDrawValueArray[1]);

            if (spanDrawValue !== 0) {
                var numberTickets = Math.floor(total / spanDrawValue);
                $("#numberTickets").text(numberTickets);
            }
            else {
                $("#numberTickets").text("0");
            }
        };

        $("#addBill").click(function(event) {

            var linkRow = $("#billInfo").clone();
            linkRow.children("td:last-child").remove();
            linkRow.find("input[type=text]").val("");
            linkRow.find("input[type=number]").val("");
            linkRow.find("select").val("");
            linkRow.append('<td><a href="#" class="deleteBill"><b>X</b></a></td>');
            $("#bottonGenerateTicket").before(linkRow);
            event.preventDefault();
            $(".deleteBill").on("click", function(event) {

                $($(this).closest("tr")).remove();
                event.preventDefault();
            });
            $(".valueBill").on("keyup", calculateFields);

        });

        $("#sorteo").change(function() {

            var value = $(this).val();
            if (value !== "") {
                $.ajax({
                    url: "../controlador/GestionBoleta.php",
                    dataType: "json",
                    type: "GET",
                    data: {
                        operation: "getDrawValue",
                        idSorteo: value
                    },
                    success: function(data) {
                        if (data.hasOwnProperty("ERROR")) {
                            response();
                            showPopupBoxMessage(item.ERROR);
                        } else {
                            $("#drawValue").val(data);
                            $("#spanDrawValue").text("$" + data);

                            calculateFields();
                        }

                    },
                    error: function(jqXHR, textStatus, thrownError) {
                        response();
                        alert("Error conecting to database...");
                    }
                });
            }
            else {
                $("#drawValue").val(0);
                $("#spanDrawValue").text("$0");
                calculateFields();
            }
        });

        $(".valueBill").on("keyup", calculateFields);

        $("#generateTicket").click(function() {
            setTimeout(function() {
                window.location = "../vista/index.php";
            }, 2000);
        });
    });
</script>